<template>
    <!-- Main content -->
    <div>
        <div class="row">
            <div class="col-xs-12">
                <theme-box title="店员列表">
                    <form class="form-inline" @submit.prevent v-el:form>
                        <form-select title="商户" :up-table="true" :sreach="true"  name="mchtId" :options="mchtList"></form-select>
                        <button type="reset" @click="reset" class="btn btn-warning pull-right">重置</button>
                        <v-button theme="primary" @click="search" class="pull-right">查询</v-button>
                    </form>
                    <table class="table table-bordered table-striped" style="width:100%" v-el:table>
                    </table>
                </theme-box>
            </div>
            <!-- /.col -->
        </div>
        <modal-container title="编辑" v-el:modal v-ref:modal class="edit-modal">
            <form @submit.prevent @reset.prevent v-el:mform>
                <div class="modal-body">
                    <table-modal :item="item" :columns-set="columnsSet"></table-modal>
                </div>

                <div class="modal-footer">
                    <v-button class="pull--left" data-dismiss="modal" @click="resetBindDrag">关闭</v-button>
                    <v-button theme="primary" type="submit">保存</v-button>
                </div>
            </form>

        </modal-container>
        <!-- /.row -->
    </div>
    <!-- /.content -->
</template>

<style lang="less" scoped>
    .form-inline .btn+.btn {
        margin-right: 10px;
    }
    .form-inline .form-group+.form-group {
        margin-left: 20px;
    }
</style>
<script>
    //解决datatables弹窗警告
    $.fn.dataTable.ext.errMode = 'none';
    import {
        dateTime,
        createDataTable
    } from 'ui/collections/general.js'
    var serialize = require('form-serialize');
    import {dateFormat} from "lib/method.js"

    var dataTable;
    var columnsSet;
    export default {
        data: () => ({
            mchtVal:'',
            mchtList:[],
            item: {},
            columnsSet: []
        }),
        methods: {
            //还原弹出框位置
            resetBindDrag() {
                this.$refs.modal._resetBindDrag();
            },
            //查询按钮
            search: function() {
                dataTable.ajax.reload();
            },
            //重置按钮
            reset: function() {
                $(".form-inline")[0].reset();
                dataTable.ajax.reload();
            },
            getMcht(data) {
                let self = this;
                var mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId
                self.$post({
                    url: "/api/v2" + projectName_Url + "/list/mcht/mchtAgent/"+ mchtId,
                    method:"GET"
                }).then(response => {
                    let list = response.content.info;
                    if(list !='' && list != [] && list != null){
                        if(list.length > 1){
                            list.unshift({key:"所有商户",value:""})
                            self.$set("mchtList", list);
                            self.mchtIdValue = list[0].value
                        }else{
                            list.unshift({key:"商户",value:""})
                            self.$set("mchtList", list);
                        }
                    }
                }, error => {});
            },
        },
        created() {
            //datatable所用数组
            columnsSet = [{
                title: "商户号",
                data: "mchtId",
                visible:false,
                readonly:true,
                className: "operate"
            }, {
                title: "商户名称",
                data: "mchtName",
                edit: true,
                readonly:true,
                className: "operate"
            },{
                title: "芸券号",
                data: "usrId",
                edit: true,
                readonly:true,
                className: "operate"
            },{
                title: "员工号",
                data: "tlrNo",
                edit: true,
                className: "operate"
            },{
                title: "店员名称",
                data: "usrName",
                edit: true,
                className: "operate"
            },{
                title: "店员类型",
                data: "usrType",
                readonly:true,
                className: "operate",
                options:[
                    {key: "店员", value: "02"},
                    {key: "店长", value: "03"},
                    {key: "老板", value: "04"}
                ],
                render: function(data) {
                    var value;
                    if(data == "02"){
                        value = '店员'
                    }else if(data == "03"){
                        value = '店长'
                    }else{
                        value = '老板'
                    }
                    return value;
                }
            },{
                title: "账号",
                data: "usrAcc",
                edit: true,
                readonly:true,
                className: "operate"
            },{
                    title: "相关操作",
                    className: "operate",
                    width: "160px",
                    render: function(value, type, row) {
                        return `
                      <button type="button" class="btn btn-primary btn-sm edit">修改</button>
                      <button type="button" class="btn btn-danger btn-sm delete">删除</button>
                      `
                    }
                }]
        },
        ready: async function() {
            dateTime({
                format: "yyyy-mm-dd",
                minView: "2"
            })
            this.$set("columnsSet", columnsSet)
            var self = this;
            self.getMcht()
            //创建dataTable
            dataTable = $(this.$els.table).DataTable({
                "columns": this.columnsSet, //定义列
                "ajax": async function(data, callback, settings) {
                    var page = [{
                        "name": "iDisplayStart",
                        "value": 1 + data.start / data.length
                    }, {
                        "name": "iDisplayLength",
                        "value": data.length
                    }];
                    //表单序列化数据
                    var _data = serialize(self.$els.form, {
                        hash: true,
                        disabled: true,
                        empty: true
                    });
                    console.log(_data)
                    _data.aoData = JSON.stringify(page);


                    //发送请求
                    var mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId
                    var result = await self.$post({
                        url: "/api/v3" + projectName_Url + "/plat/mchtusr/query/" + mchtId,
                        data:_data,
                        method: "POST"
                    })
                    if (result.respCode != "00") {
                        Midway.alert({
                            title: "操作失败",
                            content: result.content
                        })
                    }
                    callback({
                        recordsTotal: result.content.total,
                        recordsFiltered: result.content.total,
                        data: result.content.mchtusrList || []
                    })
                }
            }
            );


            $(self.$el).on("click", ".edit", function() {
                var Row = $(this).closest('tr').get(0);
                const dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
                self.item = dataArray;
                dateTime()
                //编辑框验证、保存、提交
                $(self.$els.mform).validate(self.item.valdate = {
                    async submitHandler() {
                        var form = self.$els.mform;
                        var _data = serialize(form, { hash: true, disabled:true, empty:true });
                        // return flase
                        _data.mchtId = self.item.mchtId
                        var result = await self.$post({
                            url: "/api/v3" + projectName_Url + "/plat/mchtusr/"+ self.item.usrId,
                            data: _data,
                            method: "PUT"
                        });
                        Midway.alert({title:"操作提示",content:result.errorInfo})

                        dataTable.ajax.reload(null, false);
                        $(self.$els.modal).modal('hide');
                        self.resetBindDrag()
                    },
                    rules: {
                        mchtName: {
                            required: true,
                            disabled: true
                        },
                        usrId: {
                            required: true,
                            disabled: true
                        },
                        tlrNo:{
                            required:true,
                            int:true,
                            maxlength:8
                        },
                        usrName:{
                            required:true,
                            maxlength:4
                        },
                        usrType:{
                            required: true,
                        },
                        usrAcc:{
                            required:true,
                            maxlength:10
                        },
                        loginPwd:{
                            required:true,
                            maxlength:8
                        }
                    }
                });
                $(self.$els.modal).modal('show');
            });

            $(self.$el).on("click", ".delete", async function() {
                var Row = $(this).closest('tr').get(0);
                var usrName = dataTable.row(Row).data().usrName;
                var id = dataTable.row(Row).data().usrId;

                await Midway.confirm({
                    title: "删除店员",
                    content: "是否要删除店员:" + usrName + "?"
                })
                var result = await self.$post({
                    url: "/api/v3" + projectName_Url + "/plat/mchtusr/"+id,
                    method: "DELETE"
                });
                Midway.alert({title: "操作提示", content: result.errorInfo})
                dataTable.ajax.reload();
            })
        },
        beforeDestroy() {
            $(this.$el).off("click")
        }
    }
</script>
